/**
 * 
 */
package com.demo2do.core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Determine system menu display
 * 
 * @author Downpour
 */
public class MenuSettingInterceptor extends HandlerInterceptorAdapter {
	
	private static final Log logger = LogFactory.getLog(MenuSettingInterceptor.class);
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if(logger.isDebugEnabled()) {
			logger.debug("MenuInterceptor - To determine system menu display .. ");
		}
		
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;

			// Find menu annotation on class level
			MenuSetting menuSetting = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), MenuSetting.class);

			// Only handle those controllers with menu annotation
			if (menuSetting != null) {
				request.setAttribute("activeMenu", menuSetting.value());
			}
		}
			
		return super.preHandle(request, response, handler);
	}


}
